# Importing Data
CZECK <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Israel/Czeck.xlsx")

# Checking the Imported Data
View(CZECK)

# Creating Time Series Data
CZECK_ts <- ts(CZECK, start=c(2004,1), end=c(2019,06), frequency=12)

# Viewing and Checking the Created Time Series Data
CZECK_ts
sum(is.na(CZECK_ts))
library(forecast)
CZECK_ts <- tsclean(CZECK_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(CZECK_ts)
plot(aggregate(CZECK_ts,FUN=mean))

# Decomposing
CZECK_ts_decomp <- decompose(CZECK_ts)
plot(CZECK_ts_decomp)

# Testing for Stationarity
acf(CZECK_ts, lag.max=20)
pacf(CZECK_ts, lag.max=20)

# To see any seasonal effect
boxplot(CZECK_ts~cycle(CZECK_ts))

# To remove trend effect
CZECK_ts_diff <- diff(CZECK_ts)
plot(CZECK_ts_diff)

# To remove variance effect
CZECK_ts_log <- log(CZECK_ts)
plot(CZECK_ts_log)

# To remove both (Trend and Variance) effects
CZECK_ts_both <- diff(log(CZECK_ts))
plot(CZECK_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(CZECK_ts, lag.max=20)
acf(log(CZECK_ts), lag.max=20)
acf(diff(CZECK_ts), lag.max=20)
acf(diff(log(CZECK_ts)), lag.max=20)
pacf(CZECK_ts, lag.max=20)
pacf(log(CZECK_ts), lag.max=20)
pacf(diff(CZECK_ts), lag.max=20)
pacf(diff(log(CZECK_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
CZECK_ts_model <- auto.arima(CZECK_ts)
CZECK_ts_model
CZECK_ts_model <- auto.arima(CZECK_ts, ic="aic", trace = TRUE)
CZECK_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(CZECK_ts_model$resid)
acf(CZECK_ts_model$residuals, main='ACF Residual')
pacf(CZECK_ts_model$residuals, main='ACF Residual')
Box.test(CZECK_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
CZECK_ts_forecast <- forecast (CZECK_ts_model, level=c(95), h=258)
plot(CZECK_ts_forecast)
CZECK_ts_forecast             


write.table(CZECK_ts_forecast, file="Czeck_TSA.csv", sep=",")
